package com.zhiqianbao.activity;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.User;
import com.zhiqianbao.entity.UserCheck;
import com.zhiqianbao.entity.UserIdphoto;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.File2Code;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zx.android.api.APICallback;
import com.zx.android.api.ConfigureObject;
import com.zx.android.api.ResultCode;
import com.zx.android.api.ZXApi;
import com.zx.android.api.data.IDCard;
import com.zx.android.api.data.Member;
import com.zx.android.api.data.MemberDetail;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2015/12/29.
 */
public class TakeIdCardMakePicActivity extends BaseActivity {
    String TAG = TakeIdCardMakePicActivity.class.getSimpleName();
    ZXApi api;
    /**
     * 手持身份证照片
     */
    ImageView imageViewFirstIDAuthenActivityTakeIDPic;
    String picPath = "";
    Bitmap bitmapHand;
    /**
     * 是否编辑过
     */
    boolean isHandEdit = false;
    /**
     * 身份证正面照片
     */
    ImageView imageViewFirstIDAuthenActivityTakeIDPicFront;
    String picFrontPath = "";
    Bitmap bitmapFront;
    /**
     * 是否编辑过
     */
    boolean isFrontEdit = false;
    /**
     * 身份证反面照片
     */
    ImageView imageViewFirstIDAuthenActivityTakeIDPicBack;
    String picBackPath = "";
    Bitmap bitmapBack;
    /**
     * 是否编辑过
     */
    boolean isBackEdit = false;
    /**
     * 确认按钮
     */
    Button buttonFirstIDAuthenActivityOK;
    /**
     * 通过状态
     */
    TextView textViewPicState;
    ImageView currentImageView;
    String currentImagePath;
    /**
     * 是否通过审核
     */
    boolean isChecked = false;
    /**
     * 线
     */
    View viewLine2;
    /**
     * 审核失败原因
     */
    RelativeLayout relativeLayoutMineExamineAndVerifyReason;
    /**
     * 审核失败原因内容
     */
    TextView textViewMemoId;
    private Gson gson = new Gson();
    /**
     * 图片是否需要远程下载
     */
    boolean handNeedEdit = false;
    boolean frontNeedEdit = false;
    boolean backNeedEdit = false;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RESULT_OK :
                    try{
                        imageViewFirstIDAuthenActivityTakeIDPic.setImageBitmap(bitmapHand);
                        imageViewFirstIDAuthenActivityTakeIDPicFront.setImageBitmap(bitmapFront);
                        imageViewFirstIDAuthenActivityTakeIDPicBack.setImageBitmap(bitmapBack);
                    }catch (Exception e){

                    }
                    break;
                case RESULT_CANCELED :
                default:
                    showShortToast1("连接超时");
                    break;
            }
        }
    };

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Map<String, String> param = (Map<String, String>) msg.obj;
            new SaveIdCardPic().execute(param);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_idcard_make_pic);
        init();
        initView();
    }


    private void initView() {
        try{
             imageViewFirstIDAuthenActivityTakeIDPic=(ImageView)findViewById(R.id.imageView_firstIDAuthenActivity_takeIDPic);
             imageViewFirstIDAuthenActivityTakeIDPicFront=(ImageView)findViewById(R.id.imageView_firstIDAuthenActivity_takeIDPic_front);
             imageViewFirstIDAuthenActivityTakeIDPicBack=(ImageView)findViewById(R.id.imageView_firstIDAuthenActivity_takeIDPic_back);
             buttonFirstIDAuthenActivityOK=(Button)findViewById(R.id.button_firstIDAuthenActivity_OK);
             textViewPicState=(TextView)findViewById(R.id.textView_pic_state);
             viewLine2=(View)findViewById(R.id.view_line2);
             relativeLayoutMineExamineAndVerifyReason=(RelativeLayout)findViewById(R.id.relativeLayout_mine_examine_and_verify_reason);
             textViewMemoId=(TextView)findViewById(R.id.textView_memo_id);
            //初始化真信接口
            initApi();
            //判断本地是否存在照片缓存
            List<UserIdphoto> userIdphotos = UserIdphoto.findWithQuery(UserIdphoto.class, "select * from user_idphoto where user_id = ?", Constants.LOGIN_USER.getId().toString());
            //不存在照片缓存，从服务器取出，缓存到本地
            if (userIdphotos.isEmpty()) {
                //从服务器取照片接口
                handNeedEdit = true;
                frontNeedEdit = true;
                backNeedEdit = true;
                downloadPic();
                //存在
            } else {


                UserIdphoto userIdphoto = userIdphotos.get(0);
                picPath = userIdphoto.getMobileIdCardHand();
                picFrontPath = userIdphoto.getMobileIdCardFront();
                picBackPath = userIdphoto.getMobileIdCardBack();
//            picPath = userIdphoto.getIdcardHand();
//            picFrontPath = userIdphoto.getIdcardFront();
//            picBackPath = userIdphoto.getIdcardBack();
                try{
                    //手持身份证照片
                    bitmapHand = File2Code.getBitmap(picPath, TakeIdCardMakePicActivity.this);
                    if (null == bitmapHand) {
                        handNeedEdit = true;
                    } else {
                        handNeedEdit = false;
                        imageViewFirstIDAuthenActivityTakeIDPic.setImageBitmap(bitmapHand);
                    }
                    //身份证照片正面
                    bitmapFront = File2Code.getBitmap(picFrontPath, TakeIdCardMakePicActivity.this);
                    if (null == bitmapFront) {
                        frontNeedEdit = true;
                    } else {
                        frontNeedEdit = false;
                        imageViewFirstIDAuthenActivityTakeIDPicFront.setImageBitmap(bitmapFront);
                    }
                    //身份证照片正面
                    bitmapBack = File2Code.getBitmap(picBackPath, TakeIdCardMakePicActivity.this);
                    if (null == bitmapBack) {
                        backNeedEdit = true;
                    } else {
                        backNeedEdit = false;
                        imageViewFirstIDAuthenActivityTakeIDPicBack.setImageBitmap(bitmapBack);
                    }
                }catch (Exception e){

                }

                //只要有一张图片都需要远程下载，那就远程取数据
                if (handNeedEdit || frontNeedEdit || backNeedEdit) {
                    downloadPic();
                }

            }
            //审核状态
            String infoState = Constants.LOGIN_USER.getAuditState();
            //审核通过
            if (Constants.USER_STATE_AUDIT_INFO.equals(infoState)) {
                isChecked = true;
                textViewPicState.setText("已通过");
                displayButton(View.GONE);
                //调用获取审核信息的接口，判断是否审核通过
            } else {
                isChecked = false;
                textViewPicState.setText("");
                Map<String, String> param = new HashMap<>();
                param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                new UserCheckAsyncTask().execute(param);
            }
            //绑定点击事件
            TakeCardListener listener = new TakeCardListener();
            imageViewFirstIDAuthenActivityTakeIDPic.setOnClickListener(listener);
            imageViewFirstIDAuthenActivityTakeIDPicFront.setOnClickListener(listener);
            imageViewFirstIDAuthenActivityTakeIDPicBack.setOnClickListener(listener);
            buttonFirstIDAuthenActivityOK.setOnClickListener(listener);
        }catch (Exception e){

        }
    }

    private class TakeCardListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
                if(R.id.imageView_firstIDAuthenActivity_takeIDPic==v.getId()) {
                        try {
                            showPhotoDialog(imageViewFirstIDAuthenActivityTakeIDPic);
                        } catch (Exception e) {

                        }

                }
                else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_front==v.getId()) {
                        try {
                            showPhotoDialog(imageViewFirstIDAuthenActivityTakeIDPicFront);
                        } catch (Exception e) {

                        }

                }
                else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_back==v.getId()) {
                        try {
                            showPhotoDialog(imageViewFirstIDAuthenActivityTakeIDPicBack);
                        } catch (Exception e) {

                        }
                }
                else if(R.id.button_firstIDAuthenActivity_OK==v.getId()){
                 /*   if (isHandEdit || isFrontEdit || isBackEdit) {
                        //重新上传身份证照片接口
                        new SaveIdCardPic().execute();
                    } else {
                        showShortToast("请重新上传照片");
                    }*/
                    //点击重新认证按钮，首先进行解绑操作

                    //如果已经绑定，直接获取绑定信息即可
                    api.getMemberDetail(Constants.LOGIN_USER.getId() + "", new APICallback(){
                        @Override
                        public void getMemberDetail_Callback(int code, String message, MemberDetail memberDetailOut) {
                            //如果id不存在
                            if (ResultCode.INVALID_USER == code) {
                                api.bind(Constants.LOGIN_USER.getId() + "", Constants.LOGIN_USER.getPhone(), new APICallback() {
                                    @Override
                                    public void bind_Callback(int code, String message, MemberDetail memberDetailOut) {
                                        Log.i(getClass().getSimpleName(), code + "");
                                        outputMemberDetail(code, message, memberDetailOut);
                                    }
                                });
                            } else if(ResultCode.SUCCESSED == code) {
                                outputMemberDetail(code, message, memberDetailOut);
                            }
                        }
                    });
            }
        }
    }

    private void outputMemberDetail(int code, String message, MemberDetail memberDetail) {
        Log.i(TAG, "code:" + code);
        switch (code) {
            case ResultCode.USER_CANCELED :
                return;
//            case ResultCode.USERID_ALREADY_EXIST :
//                showShortToast1("用户已经绑定");
//                break;
//            case ResultCode.IDCARD_ALREADY_EXIST :
//                showShortToast1("身份证已经注册");
//                break;
            case ResultCode.SUCCESSED :
                Member member = memberDetail.getMember();
                final IDCard idcard = memberDetail.getIdcard();
                final String idcardNum = member.idcard;
                String sex = member.sex;
                final String name = member.memberName;

                //身份证正面照片
                final String urlFront = idcard.front.imgUrl;
                //身份证地址
                final String address = idcard.front.address;
                //身份证背面照片
                final String urlFack = idcard.back.imgUrl;
                // 获得用户提交的身份证头像地址
                String urlFaceUser = idcard.front.imgFaceUrl;
                // 获得公安部的身份证头像地址
                final String urlFaceOfficial = idcard.front.imgOfficialFaceUrl;
                String realPhoto = "";
                if (member.imgUrls != null && member.imgUrls.length > 0) {
                    realPhoto = member.imgUrls[member.imgUrls.length - 1];
                }
                final String realPhoto2 = realPhoto;

                Log.i(TAG, idcardNum);
                Log.i(TAG, sex);
                Log.i(TAG, name);
                Log.i(TAG, address);
                Log.i(TAG, urlFack);
                Log.i(TAG, urlFront);
                Log.i(TAG, urlFaceUser);
                Log.i(TAG, urlFaceOfficial);

                showWaitDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap realPhotoPic = HttpUtils.getUrlImage(realPhoto2, TakeIdCardMakePicActivity.this);
                        if (!StringUtils.isBlank(realPhoto2)) {
                            Bitmap frontPic = HttpUtils.getUrlImage(urlFront, TakeIdCardMakePicActivity.this);
                            Bitmap backPic = HttpUtils.getUrlImage(urlFack, TakeIdCardMakePicActivity.this);
                            Map<String, String> param = new HashMap<>();
                            param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                            param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                            //String name, String idcard,String idcardPhoto,
                            param.put("name", name);
                            param.put("idcard", idcardNum);
                            param.put("idcardPhoto", urlFaceOfficial);
                            param.put("address", address);
                            try {
                                param.put("idcardHand", File2Code.bitmapToBase64(realPhotoPic));
                                param.put("idcardBack", File2Code.bitmapToBase64(backPic));
                                param.put("idcardFront",File2Code.bitmapToBase64(frontPic));
                                String picCachePath = FileUtils.bitmap2file(realPhotoPic);
                                String picCacheFrontPath = FileUtils.bitmap2file(frontPic);
                                String picCacheBackPath = FileUtils.bitmap2file(backPic);
                                param.put("mobileIdCardHand",picCachePath);
                                param.put("mobileIdCardBack",picCacheBackPath);
                                param.put("mobileIdCardFront",picCacheFrontPath);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            Message msg = new Message();
                            msg.obj = param;
                            handler.sendMessage(msg);
                        } else {
                            showShortToast1("真人照片获取失败");
                        }
                    }
                }).start();

                break;
        }


    }

    private void showPhotoDialog(final ImageView imageView) {
        final List<String> menus = new ArrayList<>();
        menus.add("预览大图");
        if (false) {
        //if (!isChecked) {
            menus.add("重新上传");
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(TakeIdCardMakePicActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_bank_one, null);
        TextView title = (TextView) view.findViewById(R.id.textview_bank_title);
        title.setText("选择图片位置");
        ListView listView = (ListView) view.findViewById(R.id.listView_bank);
        //修改高度
        final ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = ActionBar.LayoutParams.WRAP_CONTENT;
        listView.setLayoutParams(params);
        listView.setAdapter(new ArrayAdapter<String>(TakeIdCardMakePicActivity.this, android.R.layout.simple_list_item_1, menus));
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        dialog.show();
        //弹出框绑定方法
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (menus.get(position)) {
                    case "重新上传":
                        currentImageView = imageView;
                        if(R.id.imageView_firstIDAuthenActivity_takeIDPic==imageView.getId()) {
                                isHandEdit = true;
                        }
                        else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_front==imageView.getId()) {
                                isFrontEdit = true;
                        }
                        else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_back==imageView.getId()) {
                                isBackEdit = true;
                        }
                        getImageFromCamera();
                        break;
                    case "预览大图" :
                        Intent bigPicIntent = new Intent(TakeIdCardMakePicActivity.this, BigPicDialogActivity.class);
                        if(R.id.imageView_firstIDAuthenActivity_takeIDPic==imageView.getId()) {
                                bigPicIntent.putExtra("bitmap", picPath);
                        }
                        else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_front==imageView.getId()) {
                                bigPicIntent.putExtra("bitmap", picFrontPath);
                        }
                        else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_back==imageView.getId()) {
                                bigPicIntent.putExtra("bitmap", picBackPath);
                        }
                        startActivity(bigPicIntent);
                        break;
                }
                dialog.cancel();
            }
        });
        //关闭弹出框按钮
        TextView button = (TextView) view.findViewById(R.id.bank_dialog_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
    }

    protected void getImageFromCamera() {
        try{
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
                currentImagePath = FileUtils.getPhotopath();
                Uri uri = Uri.fromFile(new File(currentImagePath));
                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(getImageByCamera, Constants.REQUEST_CODE_CAPTURE_CAMEIA);
            } else {
                showShortToast1("请确认已经插入SD卡");
            }
        }catch (Exception e){

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case Constants.REQUEST_CODE_CAPTURE_CAMEIA:
                try{
                    Log.i(this.getClass().toString(), "拍照返回");
                    Bitmap photo = File2Code.getBitmap(currentImagePath, TakeIdCardMakePicActivity.this);
                    currentImageView.setImageBitmap(photo);
                    if(R.id.imageView_firstIDAuthenActivity_takeIDPic==currentImageView.getId()) {
                        picPath = currentImagePath;
                        bitmapHand = photo;
                    }
                    else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_front==currentImageView.getId()) {
                        picFrontPath = currentImagePath;
                        bitmapFront = photo;
                    }
                    else if(R.id.imageView_firstIDAuthenActivity_takeIDPic_back==currentImageView.getId()) {
                        picBackPath = currentImagePath;
                        bitmapBack = photo;
                    }
                    break;
                }catch (Exception e){

                }

        }
    }

    private class UserCheckAsyncTask extends AsyncTask<Map, Void, Result<UserCheck>> {
        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }
        @Override
        protected Result<UserCheck> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/userCheck", params[0], TakeIdCardMakePicActivity.this);
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<UserCheck> resultObject = Result.fromJson(result, UserCheck.class);
            return resultObject;
        }
        @Override
        protected void onPostExecute(Result<UserCheck> result) {
            if (null == result) {
                showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                return;
            }
            if(Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
              //  showShortToast1(result.getMsg());
                try{

                }catch (Exception e){

                }
                UserCheck userCheck = result.getData();
                //审核通过
                if (Constants.USER_AUDIT_STATE_SUCCESS.equals(userCheck.getCheckState())) {
                    textViewPicState.setText("已通过");
                    isChecked = true;
                    //将用户状态改为已通过审核
                    Constants.LOGIN_USER.setInfoState(Constants.USER_STATE_AUDIT_INFO);
                    //更新数据库中user状态
                    User.executeQuery("update user set info_state = ? where id = ?", Constants.USER_STATE_AUDIT_INFO, Constants.LOGIN_USER.getId().toString());
                    //隐藏失败原因
                    displayButton(View.GONE);
                } else if (Constants.USER_AUDIT_STATE_FAILED.equals(userCheck.getCheckState())) {
                    textViewPicState.setText("未通过");
                    isChecked = false;
                    displayButton(View.VISIBLE);
                    //显示审核失败原因
                    textViewMemoId.setText(userCheck.getFeedback());
                } else {
                    textViewPicState.setText("未审核");
                    isChecked =false;
                    displayButton(View.GONE);
                }
            } else {
                showShortToast1(result.getMsg());
            }
            closeWaitDialog();
        }
    }

    @Override
    protected void onDestroy() {
        try{

        }catch (Exception e){
            //回收bitmap
            imageViewFirstIDAuthenActivityTakeIDPic.setImageBitmap(null);
            imageViewFirstIDAuthenActivityTakeIDPicFront.setImageBitmap(null);
            imageViewFirstIDAuthenActivityTakeIDPicBack.setImageBitmap(null);

            if (bitmapHand != null && !bitmapHand.isRecycled()) {
                bitmapHand.recycle();
                bitmapHand = null;
            }
            if (bitmapBack != null && !bitmapBack.isRecycled()) {
                bitmapBack.recycle();
                bitmapBack = null;
            }
            if (bitmapFront != null && !bitmapFront.isRecycled()) {
                bitmapFront.recycle();
                bitmapFront = null;
            }
            System.gc();
        }



        super.onDestroy();
    }

    private void displayButton(int display) {
        viewLine2.setVisibility(display);
        relativeLayoutMineExamineAndVerifyReason.setVisibility(display);
        buttonFirstIDAuthenActivityOK.setVisibility(display);
    }

    class SaveIdCardPic extends AsyncTask<Map, Void, Result<HashMap>> {
        @Override
        protected Result<HashMap> doInBackground(Map... params) {


            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/reUploadIdCardPicZx", params[0], TakeIdCardMakePicActivity.this);
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<HashMap> resultObject = Result.fromJson(result, HashMap.class);
            return resultObject;
        }
        @Override
        protected void onPreExecute() {

        }
        @Override
        protected void onPostExecute(Result<HashMap> result) {
            if(result == null) {
                showShortToast1("连接超时！");
            } else {
                //请求成功
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    UserIdphoto idPhoto = gson.fromJson(gson.toJson(result.getData().get("idPhoto")), UserIdphoto.class);
                    User loginUser = gson.fromJson(gson.toJson(result.getData().get("user")), User.class);
                    loginUser.save();
                    UserIdphoto.deleteAll(UserIdphoto.class);
                    idPhoto.save();
                    /**
                     * 释放图片资源
                     */
                    recycleBitmap(bitmapBack);
                    recycleBitmap(bitmapFront);
                    recycleBitmap(bitmapHand);

                    TakeIdCardMakePicActivity.this.finish();
                    api.destroy();
                } else {
                    showShortToast1(result.getMsg());
                }
            }
            closeWaitDialog();
        }
    }

    private void downloadPic() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> param = new HashMap<>();
                param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/idPhotoInfo", param, TakeIdCardMakePicActivity.this);
                Message message = new Message();
                //请求失败
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_CANCELED;
                } else {
                    Result<UserIdphoto> data = Result.fromJson(result, UserIdphoto.class);
                    UserIdphoto userIdphoto = data.getData();

                    if (null == userIdphoto) {
                        message.what = RESULT_CANCELED;
                        return;
                    }

                    if (handNeedEdit) {
                        bitmapHand = HttpUtils.getUrlImage(userIdphoto.getCardHandUrl(), TakeIdCardMakePicActivity.this);
                        if (bitmapHand != null) {
                            picPath = FileUtils.bitmap2file(bitmapHand);
                        } else {
                            message.what = RESULT_CANCELED;
                        }
                    }
                    userIdphoto.setMobileIdCardHand(picPath);

                    if (frontNeedEdit) {
                        bitmapFront = HttpUtils.getUrlImage(userIdphoto.getCardFrontUrl(), TakeIdCardMakePicActivity.this);
                        if (null != bitmapFront) {
                            picFrontPath = FileUtils.bitmap2file(bitmapFront);
                        } else {
                            message.what = RESULT_CANCELED;
                        }
                    }
                    userIdphoto.setMobileIdCardFront(picFrontPath);

                    if (backNeedEdit) {
                        bitmapBack = HttpUtils.getUrlImage(userIdphoto.getCardBackUrl(), TakeIdCardMakePicActivity.this);
                        if (null != bitmapBack) {
                            picBackPath = FileUtils.bitmap2file(bitmapBack);
                        } else {
                            message.what = RESULT_CANCELED;
                        }
                    }
                    userIdphoto.setMobileIdCardBack(picBackPath);

                    userIdphoto.save();
                    message.what = RESULT_OK;
                    message.obj = userIdphoto;
                }
                mHandler.sendMessage(message);
            }
        }).start();
    }

    private void initApi() {
        api = ZXApi.getInstance();
        ConfigureObject configureObject = new ConfigureObject();
        configureObject.setAppId(Constants.CLIENT_APP_ID);
        configureObject.setAppSecret(Constants.CLIENT_APP_SECRET);
        boolean b = api.configure(this, configureObject);
        if(!b) {
            showShortToast1("初始化失败，请联系客服！");
        }
    }
}
